//
//  HomeViewController.m
//  VisitorFacetestingSystem
//
//  Created by 张斌 on 16/7/5.
//  Copyright © 2016年 YueShiKeJi. All rights reserved.
//

#import "HomeViewController.h"
#import "LoadVcManager.h"
#import "AppDelegate.h"
#import "BINbutton.h"
#import "UIView+CZFrame.h"
#import "DropdownMenuView.h"
#import "TitleMenuViewController.h"
#import "CZNetworkTool.h"
#import "InterFaceDefine.h"
#import "NSArray+Log.h"
#import "BinAleartView.h"
#import "HomeTableViewCell.h"
@interface HomeViewController ()<UITableViewDataSource,UITableViewDelegate,DropdownMenuDelegate,TitleMenuDelegate,UISearchBarDelegate>;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property(nonatomic,strong)NSMutableArray *array;//数据源


@property (nonatomic,strong)NSMutableArray *selectorPatnArray;//存放选中数据

@property (weak, nonatomic) IBOutlet UIButton *selectall;
@property (weak, nonatomic) IBOutlet UIButton *addvisitor;
@property (weak, nonatomic) IBOutlet UIButton *delete;

// 强引用button
@property (nonatomic,strong)UIButton* Mumebutton;
@property(nonatomic,strong)UIView* Meueview;

@end

@implementation HomeViewController
// 懒加载
-(NSMutableArray *)array{
    if (!_array) {

//        _array = [];
    }
    return _array;
}

- (NSMutableArray *)selectorPatnArray{
    if (!_selectorPatnArray) {
        _selectorPatnArray = [NSMutableArray array];
    }
    return _selectorPatnArray;
}

- (void)visitorcome{
    BinAleartView * alview = [BinAleartView aleartview];
    
    alview.center = self.view.center;
    
    alview.headerimageview.image = [UIImage imageNamed:@"set"];
    
    alview.visitor_name.text = @"张三到访";
    
    alview.binblock = ^(BinAleartView* aleartview){
        
        [aleartview removeFromSuperview];
    };
    
    [self.view addSubview:alview];
}

// 开始搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    
    NSDictionary* parameters = @{@"name":@"22",@"storeId":@"99"};
    
    [[CZNetworkTool sharedManager] POST:GetVisitorWithSameName parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSData*  _Nullable responseObject) {
        
        if (responseObject) {
            NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"%@",dict);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}

- (void)begingetvisitorinformation{
    // 测试获取访客记录接口
    
    NSDictionary* parameters = @{@"pageIndex":@"1",@"pageSize":@"20",@"timespan":@"0",@"storeID":@"99"};
    
    [[CZNetworkTool sharedManager] POST:GetVisitorRecordsByPage parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSData*  _Nullable responseObject) {
        
        if (responseObject) {
            NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"%@",dict);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self visitorcome];
    
    [self begingetvisitorinformation];


    
    UISearchBar* bar = [UISearchBar new];
    
    bar.frame = CGRectMake(0, 10, 100, 50);
    
    bar.delegate = self;
    
    bar.searchBarStyle = UISearchBarStyleMinimal;
    
    

    bar.barTintColor = [UIColor colorWithRed:241/255.0 green:242/255.0 blue:243/255.0 alpha:1];
    
     bar.placeholder = @"搜索";

    self.tableview.tableHeaderView = bar;
    
    //添加数据源
    self.tableview.allowsMultipleSelectionDuringEditing = YES;
    
    self.selectall.hidden = YES;
    
    self.delete.hidden = YES;

    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc ] initWithImage:[UIImage imageNamed:@"fanhuijian"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(eidting)];
    
    BINbutton * button = [BINbutton  new];
    
    self.Mumebutton = button;
    
    [button setTitle:@"全部" forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:@"down-btn"] forState:UIControlStateNormal];
    
    [button setImage:[UIImage imageNamed:@"up-btn"] forState:UIControlStateSelected];

    
    [button addTarget:self action:@selector(allclick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = self.Mumebutton;
  
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    [self.Mumebutton sizeToFit];
    
}

// 实现数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.array.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeTableViewCell* cell;
    if (indexPath.row%2!=0) {
         cell = [tableView dequeueReusableCellWithIdentifier:@"HomeCell" forIndexPath:indexPath];
    }else{
         cell = [tableView dequeueReusableCellWithIdentifier:@"HomeCell1" forIndexPath:indexPath];
    }
   
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

// 侧滑删除
-(nullable NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
//    __weak HomeViewController* weakself = self;
    
    UITableViewRowAction* deletebtn = [UITableViewRowAction rowActionWithStyle: UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }] ;
    UITableViewRowAction* updatebtn = [UITableViewRowAction rowActionWithStyle: UITableViewRowActionStyleDestructive title:@"修改" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
    }] ;
    
    updatebtn.backgroundColor = [UIColor grayColor];
    
    return @[deletebtn,updatebtn];
}

- (void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

// 选中
    if (self.tableview.editing){
    [self.selectorPatnArray addObject:self.array[indexPath.row]];
    }else {
        
        CZNetworkTool* manager = [CZNetworkTool sharedManager];

        [ manager GET:[NSString stringWithFormat:@"%@/10a40dab-9fb1-47b7-a6bd-593d7f761360/99",GetOneVisitorRecordByID] parameters: nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, NSData*  _Nullable responseObject) {
            if (responseObject) {
                NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
                NSLog(@"%@",dict);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            
        }];
        
    }
}

// 取消选中
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectorPatnArray.count>0 && self.tableview.editing) {
        [self.selectorPatnArray removeObject:self.array[indexPath.row]];
        
    }
}

// 编辑
- (void)eidting{
    
    if ([self.navigationItem.rightBarButtonItem.title isEqualToString:@"编辑"]) {
        self.tableview.allowsSelection = YES;
        //移除之前选中的内容
        if (self.selectorPatnArray.count > 0) {
            [self.selectorPatnArray removeAllObjects];
        }
        self.navigationItem.rightBarButtonItem.title = @"确定";
        //进入编辑状态
        [self.tableview setEditing:YES animated:YES];
        
        self.addvisitor.hidden = YES;
        
        self.selectall.hidden = NO;
        self.delete.hidden = NO;
        
    }else{
        self.tableview.allowsSelection = NO;
        self.navigationItem.rightBarButtonItem.title = @"编辑";
        //对选中内容进行操作
        NSLog(@"选中个数是 : %lu   内容为 : %@",(unsigned long)self.selectorPatnArray.count,self.selectorPatnArray);
        //取消编辑状态
        [self.tableview setEditing:NO animated:YES];
        
        self.addvisitor.hidden = NO;
        
        self.selectall.hidden = YES;
        self.delete.hidden = YES;
    }
    
}
// 全选
- (IBAction)allselect:(id)sender {
    
    for (int i = 0; i < self.array.count; i ++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        [self.tableview selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        
        [self.selectorPatnArray addObjectsFromArray:self.array];
        
    }
    
}

// 删除所选中
- (IBAction)deleteselect:(id)sender {
    
    //测试接口
    NSDictionary* parameters = @{@"recordIDList":@"10a40dab-9fb1-47b7-a6bd-593d7f761360,6260b23d-d38e-4b75-87ee-13657a82d04b",@"storeId":@"99"};
    
    [[CZNetworkTool sharedManager] POST:DeleteVisitorRecordsByIDList parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, NSData*  _Nullable responseObject) {
        if (responseObject) {

            NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"%@",dict);

        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    if (self.tableview.editing) {
        
        //删除
        
        [self.array removeObjectsInArray:self.selectorPatnArray];
        
        [self.tableview reloadData];
        
    }
    
    else return;
    
}
// 添加访客
- (IBAction)add:(id)sender {
    
    [self.navigationController pushViewController:[LoadVcManager sbVCWithsbname:@"AddVisitorViewController"] animated:YES];
}



- (void)allclick:(BINbutton *)sender {
  
    // 1.创建下拉菜单
    DropdownMenuView *dropdownMenuView = [[DropdownMenuView alloc] init];
    // 设置下拉菜单弹出、销毁事件的监听者
    dropdownMenuView.delegate = self;
    
    // 2.设置要显示的内容
    TitleMenuViewController *titleMenuVC = [[TitleMenuViewController alloc] init];
    titleMenuVC.dropdownMenuView = dropdownMenuView;
    titleMenuVC.delegate = self;
    
    titleMenuVC.view.w = 80 ;
    titleMenuVC.view.h = 80 ;
    dropdownMenuView.contentController = titleMenuVC;
    
    // 3.显示下拉菜单
    [dropdownMenuView showFrom:sender];
  

    
}

- (void)dropdownMenuDidDismiss:(DropdownMenuView *)menu
{
    // 让指示箭头向下
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    titleButton.selected = NO;
}

#pragma mark 下拉菜单显示了
- (void)dropdownMenuDidShow:(DropdownMenuView *)menu
{
    // 让指示箭头向上
    UIButton *titleButton = (UIButton *)self.navigationItem.titleView;
    titleButton.selected = YES;
}

#pragma mark - TitleMenuDelegate
-(void)selectAtIndexPath:(NSIndexPath *)indexPath title:(NSString *)title
{
    
    NSLog(@"indexPath = %ld", indexPath.row);
    NSLog(@"当前选择了%@", title);
    
    // 修改导航栏的标题
    [_Mumebutton setTitle:title forState:UIControlStateNormal];
    
    // 调用根据搜索条件返回相应的微博数据
    // ...
}





@end
